<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\JointFollow;
use addons\qingdongams\model\Quote as QuoteModel;
use addons\qingdongams\model\QuoteFile;
use addons\qingdongams\model\QuoteOther;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\QuoteProduct;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\File;
use addons\qingdongams\model\Product;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;


/**
 * 报价单
 */
class Quote extends StaffApi
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = [];

    //获取待审批费用数量
    public function getQuoteCheckNumber()
    {
        $faqi = QuoteModel::where([
        ])->where(function ($query) {
            $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds());
        })->count();
        $shenpi = QuoteModel::where([
            'check_status' => ['in', [0, 1]],
        ])->count();

        $this->success('请求成功', ['faqi' => $faqi, 'shenpi' => $shenpi]);
    }


    //获取报价单记录
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $where = [];
        $order = 'id desc';

        $check_status = input('check_status');//1审核中、2审核通过、3审核未通过
        $type_tab = input('type_tab', 0);
        $whereFlow = $followWhere = $whereOr = [];
        if ($check_status) {
            //1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
                $where['status'] = ['neq', 9];
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            } elseif ($check_status == 3) {
                $where['check_status|status'] = 3;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            } elseif ($check_status == 4) {
                $where['check_status'] = 4;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            } elseif ($check_status == 9) {
                $where['check_status'] = 9;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            }
        }

        if ($type_tab == 1) {//我发起的
            $whereFlow['owner_staff_id'] =['in', Staff::getMyStaffIds()];
        } elseif ($type_tab == 2) {//我审批的
            $whereFlow = $followWhere;
        }

        if (isset($params['name']) && $params['name']) {//产品名称
            $where['number'] = ['like', "%{$params['name']}%"];
        }
        if (isset($params['customer_id']) && $params['customer_id']) {
            $where['customer_id'] = $params['customer_id'];
        }
        if (isset($params['status']) && is_numeric($params['status'])) {
            $where['status'] = $params['status'];
        }
        if (isset($params['times']) && !empty($params['times'])) {
            $where['createtime'] = ['between',setTimes($params['times'], 'time')];
        }
        if (isset($params['staff_id']) && !empty($params['staff_id'])) {
            $whereFlow=[];
            $whereFlow['owner_staff_id']=$params['staff_id'];
        }
        if (isset($params['type']) && $params['type']) {//客户分类
            $whereFlow=[];
            if ($params['type'] == 1) {//我的创建
                $where['owner_staff_id'] = $this->auth->id;
            } elseif ($params['type'] == 2) {//下属创建
                $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            }else{
                $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            }
        }
        if (isset($params['createtime']) && $params['createtime']) {
            $where['createtime'] = ['between',setTimes($params['createtime'], 'time')];
        }
        if(isset($params['id_list'])){//日志 查询id列表
            $where=[];
            $whereFlow=[];
            $where['id']=['in',explode(',',$params['id_list'])];
        }
        $list = QuoteModel::where($where)->where($whereFlow)->with([
            'ownerStaff', 'customer', 'contacts'
        ])->order($order)->paginate($limit);
        $this->success('请求成功', $list);
    }


    //添加报价单
    public function addQuote()
    {
        $params = $this->request->post();
        // 表单验证

        if (($result = $this->qingdongamsValidate($params,get_class(), 'create')) !== true) {
            $this->error($result);
        }
        try {
            $result = QuoteModel::createQuote($params);
            $customerModel = new Customer();
            $customerInfo = $customerModel->where(['id' => $params['customer_id']])->find();
            if (!in_array($customerInfo['follow'], ['准备购买', '准备付款', '已经购买'])) {
                $customerModel->where(['id' => $params['customer_id']])->update(['follow' => '准备购买']);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('新增报价单成功');
        }
    }


    //修改报价单
    public function editQuote()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = QuoteModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('修改报价单信息不存在');
        }
        // 表单验证
        if (($result = $this->qingdongamsValidate($params,get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $params['status'] = 0;
            $result = QuoteModel::updateQuote($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改报价单信息成功');
    }


    //作废报价单
    public function tovoidQuote()
    {
        $id = input('id');
        $row = QuoteModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('报价单信息不存在');
        }
        if($row['owner_staff_id'] != $this->auth->id){
            $this->error('只有负责人可以作废报价单');
        }
        try {
            $result = QuoteModel::where(['id' => $id])->update(['status' => 9, 'check_status' => 9]);

            ExamineRecord::cancelExaminse(ExamineRecord::QUOTE_TYPE,$id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('作废报价单成功');
        }
        $this->error('作废失败');
    }

    /**
     * 转接报价单
     */
    public function transferQuote()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        $desc = input('desc', '无');
        if (empty($staff_id)) {
            $this->error('转接销售不能为空');
        }

        $row = QuoteModel::where(['id' => $id])->with(['customer', 'ownerStaff'])->find();
        if (empty($row)) {
            $this->error('报价单信息不存在');
        }
        if ($staff_id == $row['owner_staff_id']) {
            $this->error('当前员工已经是报价单负责人');
        }
        $newStaff = Staff::get($staff_id);
        if (empty($newStaff)) {
            $this->error('新负责人不存在');
        }
        try {
            QuoteModel::transferQuote($id,$staff_id,$desc);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('更换负责人成功');
    }

    /**
     * 报价单详情
     *
     */
    public function quoteDetail()
    {
        header('content-type:text/html;charset=utf-8');
        $id = input('id');
        $quote = QuoteModel::where(['id' => $id])->with([
            'createStaff','orderStaff', 'product', 'customer', 'contacts'
        ])->find();
        if (empty($quote)) {
            $this->error('信息不存在');
        }
        $quote = $quote->toArray();
        $quote['product_type'] = json_decode($quote['product_type']);
        $quote['clause'] = htmlspecialchars_decode(html_entity_decode($quote['clause']));
        $quote['is_operation'] = 0;
        if (in_array($quote['create_staff_id'], Staff::getLowerStaffId())) {
            //是否可以操作
            $quote['is_operation'] = 1;
        }

        if ($quote['check_status'] == 0 || $quote['check_status'] == 1) {//审核
            $quote['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::QUOTE_TYPE, $id);
        } else {
            $quote['is_examine'] = 0;
        }
        $quote['auth_login_id'] = $this->auth->id;
        $quote['files'] = File::where(['id' => ['in', explode(',', $quote['file_ids'])]])->field('id,types,name,file_path')->select();

        $quote = QuoteOther::getOther($quote);

        Message::setRead(Message::QUOTE_TYPE, $id, $this->auth->id);

        $this->success('请求成功', $quote);
    }

    //获取报价单编号
    public function getQuoteNumber()
    {
        $this->success('请求成功', ['number' => getItemNumber('quote')]);
    }

    //预览pdf
    public function previewPdf()
    {

        $params = $this->request->post();
        // 表单验证
        if (($result = $this->qingdongamsValidate($params,get_class(), 'create')) !== true) {
            $this->error($result);
        }
        try {
            unset($params['flow_staff_ids']);
            $lastId = QuoteModel::createQuote($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        QuoteModel::destroy($lastId);
        return $this->downloadQuote($lastId);
    }

    //生成pdf
    public function downloadQuote($id = null)
    {
        $type = input('type', 'word');
        if(!$id){
            $id = input('id', '');
        }
        $quote = QuoteModel::withTrashed()->where(['id' => $id])
            ->with(['customer', 'contacts','orderStaff'])->find();
        if (empty($quote)) {
            $this->error('报价单不存在');
        }

        $quote = $quote->toArray();
        $quoteProduct = QuoteProduct::where(['quote_id' => $id])->with(['product'])->select();
        $product_type = json_decode($quote['product_type'], true);
        $product_type_name = [];
        foreach ($product_type as $t) {
            $product_type_name[] = $t['name'] ?? '';
        }
        $product_type_name = implode(',', $product_type_name);
        $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/baojia1.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);

        $tmp->setValue('product_type', $product_type_name);//替换变量name
        //对齐变量
        $name = $quote['customer']['name'] ?? '';
        $name = $name . @str_repeat('　', 13 - mb_strlen($name));
        $address = $quote['customer']['address'] ?? '';
        $address = $address . @str_repeat('　', 13 - mb_strlen($address));
        $contacts = $quote['contacts']['name'] ?? '';
        $contacts = $contacts . @str_repeat('　', 13 - mb_strlen($contacts));
        $mobile = $quote['contacts']['mobile'] ?? '';
        $mobile = $mobile . @str_repeat('　', 13 - ceil(mb_strlen($mobile) / 2));
        $tmp->setValue('name', $name);//替换变量name
        $tmp->setValue('address', $address);//替换变量address
        $tmp->setValue('contacts', $contacts);//替换变量contacts
        $tmp->setValue('mobile', $mobile);//替换变量mobile

        $tmp->setValue('order_contacts', $quote['order_staff']['name']);//替换变量contacts
        $tmp->setValue('order_mobile', $quote['order_staff']['mobile']);//替换变量mobile
//        $tmp->setValue('date', date('Y年m月d日'));//替换变量date

        $rows = count($quoteProduct);//总行数
        $tmp->cloneRow('num', $rows);//复制行
        $content = '';

        for ($i = 0; $i < $rows; $i++) {
            $tmp->setValue("num#" . ($i + 1), $i + 1);//序号
            $tmp->setValue("one#" . ($i + 1), $quoteProduct[$i]['name'] ?? '');//名称
            $tmp->setValue("two#" . ($i + 1), $quoteProduct[$i]['product_type']['name'] ?? '');//规格/说明
            $tmp->setValue("three#" . ($i + 1), $quoteProduct[$i]['config_desc'] ?? '');//配置说明
            $tmp->setValue("four#" . ($i + 1), $quoteProduct[$i]['number'] ?? '');//数量
            $tmp->setValue("five#" . ($i + 1), $quoteProduct[$i]['unit'] ?? '');//单位
            $tmp->setValue("sex#" . ($i + 1), $quoteProduct[$i]['price'] ?? '');//单价
            $tmp->setValue("eight#" . ($i + 1), $quoteProduct[$i]['price']*$quoteProduct[$i]['number']?? '');//总价
            $tmp->setValue("remarks#" . ($i + 1), $quoteProduct[$i]['remarks'] ?? '');//备注

            $content .= "<br>" . $quoteProduct[$i]['description'] ?? '';
        }

        $tmp->setValue('discount_rate', $quote['discount_amount']);//替换变量mobile
        $tmp->setValue('price', $quote['quote_amount']);//替换变量mobile
        $tmp->setValue('price_big', convertAmountToCn($quote['quote_amount']));//替换变量mobile


        //start 配置
        $configs = [];
        foreach ($quoteProduct as $v) {
            if ($v['config']) {
                $pconfig = [];
                foreach ($v['config'] as $vrc) {
                    $vrc['num'] = $vrc['num'] ?? 0 * $v['number'] ?? 0;
                    $pconfig[] = $vrc;
                }
                $configs = array_merge($configs, $pconfig);
            }
        }
        $tmp->cloneRow('i', count($configs));//复制行
        $block = [];
        foreach ($configs as $k => $ves) {
            $block['i#' . ($k + 1)] = $k + 1;
            $block['cname#' . ($k + 1)] = $ves['name'];
            $block['cnum#' . ($k + 1)] = $ves['num'];
            $block['cremark#' . ($k + 1)] = $ves['remark'];
        }
        $tmp->cloneBlock('config', 1, true, false, [$block]);

        //end 配置

        //start 特约条款
        $clause = strip_tags(html_entity_decode($quote['clause']));
        $clause = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($clause)); //去除空格和换行
        $clauseList = explode('·', $clause);
        $replacements = [];
        foreach ($clauseList as $v) {
            if ($v) {
                $replacements[] = ['clause' => $v];
            }
        }
        $tmp->cloneBlock('clauseBlock', 0, true, false, $replacements);
        if(empty($clause)){
            $tmp->cloneBlock('isClause', 0);
        }else{
            $tmp->cloneBlock('isClause');
        }
        //end 特约条款


        $showNames = [];
        foreach ($quoteProduct as $v) {
            $showNames[] = $v['name'];
        }
        $products = Product::where([])->order('id asc')->column('name');
        foreach ($products as $v) {
            if (in_array($v, $showNames)) {
                //显示
                $tmp->cloneBlock($v);
            } else {
                $tmp->cloneBlock($v, 0);
            }
        }
        $filename = $quote['customer']['name'] . date('YmdHis') . '.docx';
        $fileurl = './docx/' . date('Ymd') . '/';
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();

        $file = cdnurl($model::getUrl($lastid), true);
        if ($type == 'pdf') {
            $docfile = $_SERVER['DOCUMENT_ROOT'] . trim($data['save_name'], '.'); // word文件
            $pdfdir = $_SERVER['DOCUMENT_ROOT'] . trim($fileurl, '.'); // pdf文件
            $cmd = "export HOME=/tmp && libreoffice --headless -convert-to pdf {$docfile} -outdir {$pdfdir}";
            @exec($cmd);
            $pathinfo = pathinfo($file);
            $file = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '.pdf';
            $filename = $pathinfo['filename'] . '.pdf';
        }

        $this->success('请求成功', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);;
    }
    //获取附件列表
    public function getFilesList() {
        $id = input('quote_id');

        $files = QuoteFile::where(['quote_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }

    //获取附件列表
    public function addFiles() {
        $quote_id = input('quote_id');
        $files = input('files');

        $files = QuoteFile::addFiles($files, $quote_id);
        $this->success('添加成功');
    }
    //删除附件
    public function deleteFiles() {
        $id = input('id');

        $files = QuoteFile::where(['file_id'=>$id])->delete();
        $this->success('删除成功');
    }

    //特约条款
    public function getClauseText()
    {
        $content = "· 交货期：订单生效后，5个、10个、15个、25个、30工作日内发货。<br>
· 交货地点：贵司工厂（仅限大陆工厂）/客户提供指定安装地点<br>
· 保修期：12个月或24个月<br>
· 有效期：30天、60天、90天。<br>
· 付款方式：全款发货/五五/三六一。<br>
· 含税方式：不含税/含13%增值税。";

        $this->success('请求成功', $content);
    }

}
